package com.pmt.feedplayer.di

import com.pmt.feedplayer.controller.PlayerController
import com.pmt.feedplayer.controller.TranslationController
import com.pmt.feedplayer.core.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers

/**
 * 依赖注入容器
 * 提供应用所需的各种服务和控制器
 */
class DependencyContainer {
    private val scope = CoroutineScope(Dispatchers.Main)
    
    // 懒加载的服务实例
    private val playerManager by lazy { PlayerManager.getInstance() }
    private lateinit var audioExtractor: AudioExtractor
    private lateinit var speechRecognizer: SpeechRecognizer
    private lateinit var translator: Translator
    private lateinit var subtitleManager: SubtitleManager
    
    /**
     * 初始化平台特定的翻译服务
     */
    fun initializeTranslationServices(
        audioExtractor: AudioExtractor,
        speechRecognizer: SpeechRecognizer,
        translator: Translator,
        subtitleManager: SubtitleManager
    ) {
        this.audioExtractor = audioExtractor
        this.speechRecognizer = speechRecognizer
        this.translator = translator
        this.subtitleManager = subtitleManager
    }
    
    /**
     * 获取播放器控制器实例
     */
    fun getPlayerController(): PlayerController {
        return PlayerController(
            playerManager = playerManager,
            scope = scope
        )
    }
    
    /**
     * 获取翻译控制器实例
     * 注意：使用前必须先调用initializeTranslationServices
     */
    fun getTranslationController(): TranslationController {
        if (!::audioExtractor.isInitialized) {
            throw IllegalStateException("Translation services not initialized")
        }
        
        return TranslationController(
            audioExtractor = audioExtractor,
            speechRecognizer = speechRecognizer,
            translator = translator,
            subtitleManager = subtitleManager,
            scope = scope
        )
    }
    
    /**
     * 释放所有资源
     */
    fun release() {
        // 释放播放器资源
        playerManager.release()
        
        // 释放翻译服务资源
        if (::translator.isInitialized) {
            translator.stop()
        }
        if (::speechRecognizer.isInitialized) {
            speechRecognizer.stop()
        }
        if (::audioExtractor.isInitialized) {
            audioExtractor.stop()
        }
    }
}